package lxq.away3d.tools;

import away3d.events.AssetEvent;
import away3d.events.LoaderEvent;
import away3d.loaders.Loader3D;
import away3d.loaders.parsers.Parsers;
import flash.events.EventDispatcher;

import flash.events.Event;
import flash.events.ProgressEvent;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;

class LoaderTool extends EventDispatcher{
private var loader:Loader3D;
private var ul:URLLoader;
private var format:String;

public var parser(getParser, setParser):Class;
 	private function getParser():Class {
	return _parser;
}

private function setParser(value:Class):Void {
	_parser=value;
}

private var cb:Function;
private var _parser:Class;

public function new(parser:Class=null, dataFormat:String=URLLoaderDataFormat.BINARY) {
	_parser=parser;
	format=dataFormat;
	loader=new Loader3D();
	ul=new URLLoader();
}

public function start(url:URLRequest, onCompelet:Function=null):Void {
	if (!_parser)
	throw "no parser!";
	
	ul.dataFormat=format;
	ul.addEventListener(Event.COMPLETE, onLoadCom);
	if(onCompelet!=null)
	cb=onCompelet;
	ul.load(url);
}

private function onLoadCom(event:Event):Void {
	ul.removeEventListener(Event.COMPLETE, onLoadCom);
	trace("load resource complete")
	loader.loadData(ul.data, null, null, new _parser());
	loader.addEventListener(AssetEvent.ASSET_COMPLETE, loadCom);
	loader.addEventListener(LoaderEvent.RESOURCE_COMPLETE, onResourceComplete);
	ul=null;
}

private function onResourceComplete(event:LoaderEvent):Void {
	loader.removeEventListener(LoaderEvent.RESOURCE_COMPLETE, onResourceComplete);
	loader.removeEventListener(AssetEvent.ASSET_COMPLETE, loadCom);
	trace("parser resource complete");
	dispatchEvent(new Event("parseComplete"));
	dispose();
}

private function loadCom(e:AssetEvent):Void {
	cb(e);
}

public function dispose():Void {
	loader.removeEventListener(AssetEvent.ASSET_COMPLETE, loadCom);
	loader.disposeAsset();
	loader.dispose();
	loader=null;
	cb=null;
	ul=null;
}
public var complete(null, setComplete):Function;
 	private function setComplete(value:Function):Void{
	loader.addEventListener(AssetEvent.ASSET_COMPLETE,value);
	cb=value;
}
public var error(null, setError):Function;
 	private function setError(value:Function):Void{
	loader.addEventListener(LoaderEvent.LOAD_ERROR,value);
}
public var progress(null, setProgress):Function;
 	private function setProgress(value:Function):Void{
	ul.addEventListener(ProgressEvent.PROGRESS,value);
}
}